/**
 * create by Jane
 * 链接数据库安装配置
 */
import tcb from "tcb-js-sdk";
import config from "../../cloudbaserc.json";

export const app = tcb.init({
    env: config.envId,
});
const auth = app.auth();
export const db = app.database();

/**
 * 匿名登录
 * @returns {Promise<boolean>}
 */
export const login = async () => {
    await auth.anonymousAuthProvider().signIn();
    // 匿名登录成功检测登录状态isAnonymous字段为true
    const loginState = await auth.getLoginState();
    console.log('匿名登录 ==> ', loginState.isAnonymousAuth);
    return loginState.isAnonymousAuth;
}

/**
 * 设置腾讯云加载的云图片信息
 * @data 操作的数据源
 * @key data数组下需要渲染的key
 * @returns {Promise<void>}
 */
export const setTcbCloudImages = async (data, key = 'img') => {
    let fileList = [];
    data.forEach((item) => {
        if (item[key]) {
            fileList.push(item[key]);
        }
    });
    if (fileList.length) {
        const file = await app.getTempFileURL({fileList});
        const files = file.fileList || [];
        data.forEach((item, index) => {
            if (item[key]) {
                item[key] = files[index]['tempFileURL'];
            }
        })
    }
    return data;
}